﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace DataCenter.Share
{
    public class RecentValueManager
    {
        private RecentValueManager()
        {

        }
        private static RecentValueManager Instance = null;
        public static RecentValueManager GetInstance()
        {
            if (Instance == null)
                Instance = new RecentValueManager();
            return Instance;
        }

        public void UpdateRecentValue(SqlCommand command, int objectId, int valueType, DateTime valueTime, float value)
        {
            string commandString = @"SELECT ValueTime FROM RecentValueTable WHERE ObjectId = @ObjectId AND ValueType = @ValueType";
            command.CommandText = commandString;
            command.CommandType = CommandType.Text;
            command.Parameters.AddWithValue("@ObjectId", objectId);
            command.Parameters.AddWithValue("@ValueType", valueType);
            command.Parameters.AddWithValue("@ValueTime", valueTime);
            command.Parameters.AddWithValue("@R__0", value);
            object oValue = command.ExecuteScalar();
            if (oValue == null || oValue == DBNull.Value)
            {
                commandString = @"INSERT INTO RecentValueTable(ObjectId, ValueType, ValueTime, R__0)
                                  VALUES(@ObjectId, @ValueType, @ValueTime, @R__0)";
                command.CommandText = commandString;
                command.CommandType = CommandType.Text;
                command.ExecuteNonQuery();
            }
            else
            {
                DateTime lastTime = Convert.ToDateTime(oValue);
                if (valueTime >= lastTime)
                {
                    commandString = @"UPDATE RecentValueTable SET ValueTime = @ValueTime, R__0 = @R__0
                                    WHERE ObjectId = @ObjectId AND ValueType = @ValueType";
                    command.CommandText = commandString;
                    command.CommandType = CommandType.Text;
                    command.ExecuteNonQuery();
                }
            }
            command.Parameters.Clear();
        }
    }
}
